/**
 * Created by Administrator on 2018-02-08.
 */

var TimerUtil=function (input, delay) {
    this.init(input, delay)
};

TimerUtil.prototype = {
    time: 0,
    state: true,
    delay: 1,
    begin: null,
    timeId: 0,
    input: null,

    init: function (input, delay) {
        if (!/^[0-9]*[1-9][0-9]*$/.test(delay)) throw new TypeError("delay is not a natural number!");
        this.delay = delay | this.delay;
        this.input = $(input);
    },

    start: function () {
        if (this.state) {
            this.state = false;
            this.begin = new Date().getTime();
            this.timeId = window.setInterval(this.run.bind(this), this.delay);
        }
    },

    stop: function () {
        clearInterval(this.timeId);
        this.time = new Date().getTime() - this.begin;
        this.input.val(this.format(':'));
        this.state = true;
    },

    run: function () {
        this.time = new Date().getTime() - this.begin;
        this.input.val(this.format(':'));
    },

    format: function (split) {
        var s = this.time % 1000;
        var ss = parseInt(this.time / 1000) % 60;
        var m = parseInt(this.time / 1000 / 60);

        return (m.toString().length === 1 ? '0' + m.toString() : m) + (split === 'z' ? '分' : split)
            + (ss.toString().length === 1 ? '0' + ss.toString() : ss) + (split === 'z' ? '秒' : split)
            + (s.toString().length === 1 ? '00' + s.toString() : s.toString().length === 2 ? '0' + s.toString() : s);
    },

    toString: function () {
        return this.format('z')
    }
};